<template>
  <div class="blog-container w-full flex justify-between">
    <div class="blog-content prose prose-lg max-w-none shadow-md border-[#e4d6f5] w-4/5">
      <ContentRenderer :value="article ? article : {}" />
    </div>
    <div class="w-1/5">
      <div class="sticky-container sticky" :style="{ top: topDistance + 'px' }">
        <div class="toc shadow-md border-[#e4d6f5] rounded-md">
          <h1 class="text-2xl font-bold text-center text-[#4b2a93] sticky top-0 bg-[#fdfcfe] mb-4">文章目录</h1>
          <div class="toc-content">
            <div @click="goToTitle(item.id)" class="toc_item mb-4 text-xl" v-for="item in article?.body?.toc?.links"
              :key="item.id">
              <h2>{{ item.text }}</h2>
            </div>
          </div>
        </div>
        <div class="ai shadow-md border-[#e4d6f5] rounded-md mt-4">
          <div class="flex flex-col items-center justify-center" v-if="chatList.length === 0">
            <img src='/public/deepseek.svg' alt="AI" class="rounded-full w-28 h-28">
            <h1 class="my-3 text-[#4b5563]">我是 DeepSeek，很高兴见到你!</h1>
            <h1 class="text-[#4b5563]">如果文中有不懂的地方就问问我吧!</h1>
            <el-input class="mt-3" v-model="submit" placeholder="给DeepSeek发送消息" @change="sendMessage"></el-input>
          </div>
          <div class=" w-full h-full relative" v-else>
            <div class="aiChat overflow-y-auto h-[calc(100%-4rem)] px-2" ref="aiChatRef">
              <div v-for="item in chatList" :key="item.id" class="w-full mb-4">
                <div v-if="item.role === 'user'" class="flex justify-end">
                  <div class="inline-block border rounded-md shadow-md p-2 bg-[#f5f3ff]">
                    <p class="text-sm text-[#4b5563]">{{ item.text }}</p>
                  </div>
                </div>
                <div v-else class="flex justify-start">
                  <div class="inline-block border rounded-md shadow-md p-2 bg-[#f5f3ff]">
                    <p v-if="item.isTyping" class="text-sm text-[#4b5563]">{{ item.text }}</p>
                    <div v-else class="prose2 prose-lg max-w-none  pl-1">
                      <div v-html="render"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="sticky bottom-0 pt-6 bg-[#fdfcfe]">
              <el-input v-model="submit" placeholder="给DeepSeek发送消息" @change="sendMessage"></el-input>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { marked } from 'marked'
interface chat {
  text: string
  role: string
  isTyping?: boolean
  id: string
}

const route = useRoute()
const article = ref<any>(null)
const topDistance = ref(0)
const tabarTop = ref(0)
const chatList = reactive<chat[]>([])
const submit = ref('')
const render = ref()
const aiChatRef = ref<HTMLElement | null>(null)

article.value = await useAsyncData(
    `article-${route.params.slug}`,
    () => queryCollection('blog').where('path', '=', `/blog/${route.params.slug}`).first()
  )

const sendMessage = async () => {
  if (!submit.value.trim()) return
  try {
    chatList.push({
      text: submit.value,
      role: 'user',
      id: Math.random().toString(36).substring(2, 15)
    })
    scrollToBottom()
    let assistantMessageId = Math.random().toString(36).substring(2, 15)
    const assistantMessage: chat = {
      text: '',
      role: 'assistant',
      isTyping: true,
      id: assistantMessageId
    }

    chatList.push(assistantMessage)

    const stream = await deepSeek(submit.value)
    submit.value = ''

    for await (const chunk of stream) {
      const content = chunk.choices[0]?.delta?.content || ''
      if (content) {
        const index = chatList.findIndex(item => item.id === assistantMessageId)
        if (index !== -1) {
          chatList[index].text += content
          await nextTick()
          scrollToBottom()
        }
      }
    }

    const index = chatList.findIndex(item => item.id === assistantMessageId)
    if (index !== -1) {
      chatList[index].isTyping = false
      submit.value = ''
      console.log(chatList[index].text, 'chatList[index].text')
      render.value = marked(chatList[index].text)
      console.log(render.value, 'render')
      scrollToBottom()
    }


  } catch (error) {
    console.error('发送消息失败:', error)
  }
}

const goToTitle = (id: string) => {
  const element = document.getElementById(id)
  if (element) {
    window.scrollTo({
      top: element.getBoundingClientRect().top + window.scrollY - tabarTop.value - 20,
      behavior: 'smooth'
    })
  }
}

function scrollToBottom() {
  nextTick(() => {
    if (aiChatRef.value) {
      aiChatRef.value.scrollTop = aiChatRef.value.scrollHeight
    }
  })
}

onMounted(async () => {
  tabarTop.value = parseInt(localStorage.getItem('tabarTop') || '0')
  const blogContent = document.querySelector('.blog-content')
  if (blogContent) {
    topDistance.value = blogContent.getBoundingClientRect().top
  }
  article.value = article.value.data
  console.log(article.value)

  // 在数据加载完成后设置标题
  if (article.value?.title) {
    useHead({
      title: article.value.title
    })
  }
})
</script>

<style scoped>
.blog-container {
  margin: 0 auto;
  padding: 2rem;
}

.toc {
  background: #fdfcfe;
  border-radius: 8px;
  padding: 2rem;
}

.toc-content {
  height: calc(40vh - 9rem);
  overflow-y: auto;
  padding-right: 0.5rem;
}

.toc-content::-webkit-scrollbar {
  width: 4px;
}

.toc-content::-webkit-scrollbar-thumb {
  background-color: #4b2a93;
  border-radius: 4px;
}

.toc-content::-webkit-scrollbar-track {
  background-color: #f5f3ff;
}

.aiChat::-webkit-scrollbar {
  width: 4px;
}

.aiChat::-webkit-scrollbar-thumb {
  background-color: #4b2a93;
  border-radius: 4px;
}

.aiChat::-webkit-scrollbar-track {
  background-color: #f5f3ff;
}

.toc_item {
  cursor: pointer;
  color: #4b5563;
}

.toc_item:hover {
  color: #4b2a93;
}

.ai {
  background: #fdfcfe;
  border-radius: 8px;
  padding: 2rem;
  overflow-y: auto;
  height: calc(60vh - 8rem);
}

.blog-content {
  margin-right: 1rem;
  background: #fdfcfe;
  border-radius: 8px;
  padding: 2rem;
}

/* Markdown 内容样式 */
:deep(.prose) {
  color: inherit;
}

:deep(.prose h1) {
  font-size: 2.25rem;
  margin-top: 0;
  margin-bottom: 1rem;
  font-weight: 700;
  color: #4b2a93;
}

:deep(.prose h2) {
  font-size: 1.875rem;
  margin-top: 2rem;
  margin-bottom: 1rem;
  font-weight: 600;
  color: #4b2a93;
}

:deep(.prose h3) {
  font-size: 1.5rem;
  margin-top: 1.5rem;
  margin-bottom: 1rem;
  font-weight: 500;
  color: #4b2a93;
}

:deep(.prose p) {
  margin-top: 1.25rem;
  margin-bottom: 1.25rem;
  line-height: 1.75;
  color: #4b5563;
  font-size: 1.25rem;
}

:deep(.prose a) {
  color: #4b2a93;
  text-decoration: none;
}

:deep(.prose code) {
  background-color: #f5f3ff;
  color: #4b2a93;
  padding: 0.2em 0.4em;
  border-radius: 0.25rem;
}

:deep(.prose pre) {
  background-color: #f5f3ff;
  color: #4b2a93;
  padding: 1rem;
  border-radius: 0.5rem;
  overflow-x: auto;
}

:deep(.prose blockquote) {
  border-left: 4px solid #4b2a93;
  padding-left: 1rem;
  font-style: italic;
  color: #4b5563;
  background-color: #f5f3ff;
}

:deep(.prose ul) {
  list-style-type: disc;
  padding-left: 1.5rem;
  color: #4b5563;
  font-size: 1.25rem;
}

:deep(.prose ol) {
  list-style-type: decimal;
  padding-left: 1.5rem;
  color: #4b5563;
  font-size: 1.25rem;
}

:deep(.prose li) {
  margin: 0.5rem 0;
}

:deep(.prose img) {
  max-width: 100%;
  height: auto;
  border-radius: 0.5rem;
  margin: 1.25rem 0;
}

:deep(.prose table) {
  width: 100%;
  border-collapse: collapse;
  margin: 1.25rem 0;
  font-size: 1.25rem;
}

:deep(.prose th) {
  background-color: #e4d6f5;
  padding: 0.75rem;
  border: 1px solid #4b2a93;
  color: #4b2a93;
}

:deep(.prose td) {
  padding: 0.75rem;
  border: 1px solid #e4d6f5;
  color: #4b5563;
}

:deep(.prose hr) {
  border: 0;
  border-top: 1px solid #e4d6f5;
  margin: 1.5rem 0;
}

.meta-info {
  color: #9ca3af;
  font-size: 0.875rem;
}

:deep(.el-input__inner) {
  /* 输入框内部样式 */
  background-color: #fdfcfe;
  color: #4b5563;
}

:deep(.el-input__inner:focus) {
  /* 输入框聚焦时的样式 */
  border-color: #a855f7;
}

:deep(.el-input__wrapper) {
  /* 输入框外层容器样式 */
  background-color: #fdfcfe;
  border: 2px solid #e4d6f5;
  box-shadow: none;
}



/* 缩小版 Markdown 样式 */
:deep(.prose2) {
  color: inherit;
  font-size: 0.875rem;
  line-height: 1.5;
}

:deep(.prose2 h1) {
  font-size: 1.5rem;
  margin-top: 0;
  margin-bottom: 0.75rem;
  font-weight: 700;
  color: #4b2a93;
}

:deep(.prose2 h2) {
  font-size: 1.25rem;
  margin-top: 1.5rem;
  margin-bottom: 0.75rem;
  font-weight: 600;
  color: #4b2a93;
}

:deep(.prose2 h3) {
  font-size: 1.125rem;
  margin-top: 1.25rem;
  margin-bottom: 0.75rem;
  font-weight: 500;
  color: #4b2a93;
}

:deep(.prose2 p) {
  margin-top: 0.75rem;
  margin-bottom: 0.75rem;
  line-height: 1.5;
  color: #4b5563;
  font-size: 0.875rem;
}

:deep(.prose2 a) {
  color: #4b2a93;
  text-decoration: none;
}

:deep(.prose2 code) {
  background-color: #efe4fc;
  color: #4b2a93;
  padding: 0.1em 0.3em;
  border-radius: 0.25rem;
  font-size: 0.875rem;
}

:deep(.prose2 pre) {
  background-color: #efe4fc;
  color: #4b2a93;
  padding: 0.75rem;
  border-radius: 0.375rem;
  overflow-x: auto;
  font-size: 0.875rem;
}

:deep(.prose2 blockquote) {
  border-left: 3px solid #4b2a93;
  padding-left: 0.75rem;
  font-style: italic;
  color: #4b5563;
  background-color: #e4d6f5;
  margin: 0.75rem 0;
}

:deep(.prose2 ul) {
  list-style-type: disc;
  padding-left: 1.25rem;
  color: #4b5563;
  font-size: 0.875rem;
  margin: 0.75rem 0;
}

:deep(.prose2 ol) {
  list-style-type: decimal;
  padding-left: 1.25rem;
  color: #4b5563;
  font-size: 0.875rem;
  margin: 0.75rem 0;
}

:deep(.prose2 li) {
  margin: 0.25rem 0;
}

:deep(.prose2 img) {
  max-width: 100%;
  height: auto;
  border-radius: 0.375rem;
  margin: 0.75rem 0;
}

:deep(.prose2 table) {
  width: 100%;
  border-collapse: collapse;
  margin: 0.75rem 0;
  font-size: 0.875rem;
}

:deep(.prose2 th) {
  background-color: #e4d6f5;
  padding: 0.5rem;
  border: 1px solid #4b2a93;
  color: #4b2a93;
}

:deep(.prose2 td) {
  padding: 0.5rem;
  border: 1px solid #e4d6f5;
  color: #4b5563;
}

:deep(.prose2 hr) {
  border: 0;
  border-top: 1px solid #e4d6f5;
  margin: 1rem 0;
}

/* 表格内容自动换行 */
:deep(.prose table),
:deep(.prose2 table) {
  table-layout: auto;
  word-break: break-all;
  white-space: pre-line;
  max-width: 100%;
  overflow-x: auto;
  display: block;
}

/* 代码块内容自动换行且可横向滚动 */
:deep(.prose pre),
:deep(.prose2 pre) {
  white-space: pre-wrap;
  word-break: break-all;
  overflow-x: auto;
  max-width: 100%;
}

/* 美化横向滚动条 */
:deep(.prose pre::-webkit-scrollbar),
:deep(.prose2 pre::-webkit-scrollbar),
:deep(.prose table::-webkit-scrollbar),
:deep(.prose2 table::-webkit-scrollbar) {
  height: 6px;
  background: #f5f3ff;
}

:deep(.prose pre::-webkit-scrollbar-thumb),
:deep(.prose2 pre::-webkit-scrollbar-thumb),
:deep(.prose table::-webkit-scrollbar-thumb),
:deep(.prose2 table::-webkit-scrollbar-thumb) {
  background: #c4b5fd;
  border-radius: 3px;
}
</style>
